require "gadgets/frame"

module MapEditor
  module PaletControler
    class PaletPicker      
      def on_left_down(e)
        @target.frame.set_size(1, 1)
        tx = ((e.x + @target.scroll_x) / @target.zoomed_grid_width).floor
        ty = ((e.y + @target.scroll_y )/ @target.zoomed_grid_height).floor
        @target.select(tx, ty)
      end
      
      def target=(target)
        @target = target
      end
    
      def on_left_up(e)

      end

      def on_right_down(e)
        @target.frame.set_size(1, 1)
      end

      def on_right_up(e)
        @target.frame.set_size((@target.ex - @target.sx).abs + 1, (@target.ey - @target.sy).abs + 1)
      end

      def on_motion(e)
        return if @target.chipset.nil?
        
        if @target.left_pressed
          tx = ((e.x + @target.scroll_x) / @target.zoomed_grid_width).floor
          ty = ((e.y + @target.scroll_y) / @target.zoomed_grid_height).floor
          if tx >= @target.scroll_x_count && ty >= @target.scroll_y_count && tx < (@target.x_count + @target.scroll_x_count) && ty < (@target.y_count + @target.scroll_y_count)
            @target.ex = tx
            @target.ey = ty
          end
          @target.frame.set_size((@target.ex - @target.sx).abs + 1, (@target.ey - @target.sy).abs + 1)
        end
        
        @target.render
      end
      
      def on_double_clicked(e)
      
      end
      
      def render(s)
        @target.frame.render(s, @target.grid_width, @target.grid_height, [@target.sx, @target.ex].min - @target.scroll_x_count, [@target.sy, @target.ey].min - @target.scroll_y_count)
      end
      
      def render_detail(s)
      
      end
    end
  end
end